//
//  SYStatusPictureView.swift
//  SingWeibo
//
//  Created by shiying on 15/12/21.
//  Copyright © 2015年 shiying. All rights reserved.
//

import UIKit
import SDWebImage

let SYStatusPictureViewCellSelectNotification = "SYStatusPictureViewCellNotification"
let SYStatusPictureViewCellSelectIndexPathKey = "SYStatusPictureViewCellSelectIndexPathKey"
let SYStatusPictureViewCellSelectModelsKey = "SYStatusPictureViewCellSelectModelsKey"

class SYStatusPictureView: UICollectionView {
    
    let ReuseIdentifier = "StatusPictureViewReuseIdentifier"
    
    var status: SYStatus? {
        didSet {
            self.reloadData()// 刷新数据
        }
    }
    
    /// 流水布局
    private var layout = UICollectionViewFlowLayout()
    
    func calcViewSize() ->CGSize {
        /// 设置itemSize 的高宽
        let itemSize = CGSize(width: 90, height: 90)
        
        /// 设置间距
        let margin:CGFloat = 10
        
        /// itemSize
        layout.itemSize = itemSize
        
        /// 间距
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        let count = status?.pictureURLs?.count ?? 0
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            var size = CGSize(width: 150, height: 120)
            
            let url = status!.pictureURLs![0]  // 由于不知道新浪微博图片的的大小 所以下载一张图片的大小
            
            // key 图片url地址, string类型
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url.absoluteString) {
                size = image.size // 将图片大小设置为size
            }
            // 如果图片小于 40 那么等于40
            if size.width < 40 {
                size.width = 40
            } else if size.width > UIScreen.mainScreen().bounds.width * 0.5 {
                size.width = UIScreen.mainScreen().bounds.width * 0.5 //如果大于一半，那就就等于一半
            }
            
            
            layout.itemSize = size
            return size
        }
        
        if count == 4 { // 第一行都是二张，中间有间距
            let value = 2 * itemSize.width + margin
            return CGSize(width: value, height: value)
        }
        
        /// 列数
        let columu = 3
        
        /// 宽  （列数 * 宽 + 列数 - 1） * margin  如: 3 * 90 + 2 *间距
        let width = CGFloat(columu) * itemSize.width + (CGFloat(columu) - 1) * margin
        
        /// 行数  （个数 + 列数 - 1） / 列数  如：（5 + 3 - 1） / 3
        let row = (count + columu - 1) / columu
        
        /// 高
        let heiht = CGFloat(row) * itemSize.height + (CGFloat(row) - 1) * margin
        
        return CGSize(width: width, height: heiht)
    }

    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout) // 调用父类
        
        //MARK: - 注册Cell
        self.registerClass(SYStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        /// 数据源
        self.dataSource = self
        self.delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//MARK: - 分类 实现数据源方法
extension SYStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0  // 要么有数据，要么是0行
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! SYStatusPictureViewCell
        
        cell.imageURL = status?.pictureURLs![indexPath.item] /// 获取到图片的地址
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        let pic_url = status!.pic_urls![indexPath.item]
//        let large = status!.largePictureURLs![indexPath.item]
//        print("pic_url\(pic_url),\n large\(large)")
//        
        // 因为转场动画时需要知道缩略图iamgeView的位置和图片，创建模型数组
        var photoBrowserModels = [SYPhotoBrowserModel]()
        
        // 获取配图的数量
        let count = self.status!.largePictureURLs!.count
        
        // 遍历每一个缩略图上，来创建模型数组
        for i in 0..<count {
            // 创建模型
            let model = SYPhotoBrowserModel()
            
            // 设置模型大图的url
            let url = self.status!.largePictureURLs![i]
            model.largeURL = url
            
            //获取cell
            let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: i, inSection: 0)) as! SYStatusPictureViewCell
            
            // 设置模型小图
            model.imageView = cell.imageView
            // 添加到模型数组
            photoBrowserModels.append(model)
            
        }
        // 点击了Cell 发出通知，将点击的cell和大图的数组传出去
        NSNotificationCenter.defaultCenter().postNotificationName(SYStatusPictureViewCellSelectNotification, object: self, userInfo: [SYStatusPictureViewCellSelectIndexPathKey : indexPath,
            SYStatusPictureViewCellSelectModelsKey : photoBrowserModels
            ])
        
        
    }
    
    
}

//MARK: - Cell
class SYStatusPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet{
            imageView.sd_setImageWithURL(imageURL) //SDWebView 方法下载图片，将imageURL传了过来
            // 判断一个地址是否是gif地址
            let gif = imageURL!.absoluteString.lowercaseString.hasSuffix("gif")
            // 如果是gif图片才显示 gif图标
            gifImageView.hidden = !gif
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    /// 准备UI
    func prepareUI() {
        contentView.addSubview(imageView) /// 添加图片
        contentView.addSubview(gifImageView)
        imageView.ff_Fill(contentView) /// 填充
        gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: contentView, size: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 懒加载
    lazy var imageView: UIImageView = {
        let imageView = UIImageView(image: nil)
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
    
        return imageView
    }()
    
    private lazy var gifImageView: UIImageView = {
        let imageView = UIImageView()
    
        imageView.image = UIImage(named: "timeline_image_gif")
        return imageView
    }()
}
